import getApiData, { postCPASToolsAipsData } from '@/services/cpasRequest';
import { Modal } from 'antd';
import { TreeList } from 'devextreme-react';
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import DevPopup from '~/public/cpas-ui/components-ui/express-components/DevPopup/DevPopup';
import SetStandardType from './SetStandardType';
import './_style.less';
import notify from 'devextreme/ui/notify';
import { nanoid10 } from "~/public/cpas-business/tools/Tools";

export interface propsData {
  dbname: string | any;
  dataId?: string | any;
  title?: string | any;
  okCallback?: (isTrue: boolean) => void; //成功回调
  cancelCallback?: () => void; //失败回调
  modalProps?: any; //Modal属性{},如zindex
}

const BusinessTypeModal = React.forwardRef((props: propsData, ref: any) => {
  const { dbname, dataId, cancelCallback, okCallback, title = '设置标准业务类型' } = props;

  const [defaultSource, setDefaultSource] = useState<any>([]); //原始数据
  const [dataSource, setDataSource] = useState<any>([]);
  const [standardSource, setStandardSource] = useState<any>([]);
  const [isReportModalOpen, setReportModalOpen] = useState<boolean>(false);
  const [isBatchButton, setBatchButton] = useState(true);
  // const [rowData, setRowData] = useState<any>({}); //当前行数据
  const updateRowData = useRef<any>();//当前行数据
  // const [selectedRowsData, setSelectedRowsData] = useState<any>([]); //当前勾选数据
  const InputRef = useRef<any>();
  const treeListRef = useRef<any>();
  const setStandardTypeRef = useRef<any>();
  const updateSelectedRowsData = useRef<any>(); //当前勾选数据
  const [tableKey, setTableKey] = useState<string>(nanoid10());
  // const [isClickBatchClear, setClickBatchClear] = useState<boolean>(false);
  // lastScrollTop 用于记录上一次滚动条的位置
  // const treeScrollRef = useRef<any>(0);
  useImperativeHandle(ref, () => ({
    show: async () => {
      setReportModalOpen(true);
    },
    close: () => {
      setReportModalOpen(false);
    },
  }));
  // 获取业务类型项目
  const getBusinessType = async () => {
    try {
      const res = await getApiData('get.BAS_Transaction_Type', { dbname });
      const data = res?.data;
      if (data && data.length) {
        const temp = [];
        for (let i = 0; i < data.length; i++) {
          const { mainType } = data[i];
          if (mainType === "null") {
            data[i].mainType = '';
          }
          data[i].key = i;
          temp.push({
            ...data[i],
          });
        }
        setDefaultSource(temp);
        setDataSource(data);
      }
    } catch (error) {
      console.log(error);
    }
  };
  // 获取业务类型项目
  const getTypName = async () => {
    try {
      const res = await postCPASToolsAipsData('localJsonData', {
        dataName: 'BAS_mainType',
        action: 'get',
      });
      const data = res?.data;
      if (data && data.length) {
        const temp = [];
        for (let i = 0; i < data.length; i++) {
          temp.push({
            key: i,
            id: data[i],
            name: data[i],
          });
        }
        const result: any = temp.filter((item) => item.name === "清空");
        if (!result || !result.length) {
          temp.push({
            key: temp.length,
            id: null,
            name: ""
          })
        }
        setStandardSource(temp);
      }
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    getBusinessType();
  }, [dbname, isReportModalOpen]);

  useEffect(() => {
    getTypName();
  }, [dbname]);

  // useEffect(() => {
  //   if(treeListRef?.current) {
  //     setTimeout(() => {
  //       const n_TreeViewScrollView = treeListRef?.current?.instance?.getScrollable();
  //       n_TreeViewScrollView.scrollTo({
  //         // left: 0,
  //         top: treeScrollRef.current,
  //       });
  //     }, 300);
  //   }
  // }, [isBatchButton]);

  //更新业务类型
  const updateBusinessType = async (typeName: string, mainType = null) => {
    try {
      const res = await getApiData('update.BAS_Transaction_Type', { dbname, typeName, mainType });
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  };

  /**
   * 批量设置
   */
  const onBatchSet = (e: any) => {
    const rowData = updateRowData?.current ? updateRowData?.current : null;
    const selectedRowsData = updateSelectedRowsData.current;
    if (!selectedRowsData || !selectedRowsData.length) {
      return notify(`请勾选需要设置的类型名称～`, 'warning', 2000);
    }
    if (rowData && selectedRowsData && selectedRowsData.length) {
      //批量数据对比更新
      const mainType = rowData.mainType;
      if (mainType) {
        for (let i = 0; i < selectedRowsData.length; i++) {
          for (let j = 0; j < dataSource.length; j++) {
            if (selectedRowsData[i]?.typeName === dataSource[j]?.typeName) {
              dataSource[j].mainType = mainType;
            }
          }
        }
        setDataSource([...dataSource]);
      }
    }
  };
  const onBatchClear = async (e: any) => {
    console.log(e, 'clear');
    const selectedRowsData = updateSelectedRowsData?.current;
    if (!selectedRowsData || !selectedRowsData.length) {
      return notify(`请勾选需要清空的类型名称～`, 'warning', 2000);
    }
    if (selectedRowsData && selectedRowsData) {
      for (let i = 0; i < dataSource.length; i++) {
        const { typeName } = dataSource[i];
        for (let j = 0; j < selectedRowsData.length; j++) {
          const { typeName: newTypeName } = selectedRowsData[j];
          if (typeName === newTypeName) {
            dataSource[i].mainType = null;
          }
        }
      }
      setDataSource([...dataSource]);
    }
    // setClickBatchClear(true);
    // treeListRef?.current?.instance?.clearSelection();
    // await getBusinessType();
  }
  const columns = [
    {
      caption: '类型名称',
      dataField: 'typeName',
      allowEditing: false,
    },
    {
      caption: '标准业务类型',
      dataField: 'mainType',
      lookup: {
        dataSource: standardSource,
        valueExpr: 'id',
        displayExpr: 'name',
      },
    },
  ];
  const toolbar: any = {
    items: [
      {
        widget: 'dxButton',
        name: 'e',
        location: 'before',
        options: {
          text: '设置标准业务类型',
          icon: 'edit',
          type: 'normal',
          class: 'user-type-button',
          onClick: () => {
            // setClickBatchClear(false);
            setStandardTypeRef?.current?.show();
          },
        },
      },
      {
        widget: 'dxButton',
        name: 'e',
        location: 'before',
        options: {
          text: '批量设置',
          type: 'default',
          onClick: onBatchSet,
          // disabled: isBatchButton,
        },
      },
      {
        widget: 'dxButton',
        name: 'e',
        location: 'before',
        options: {
          text: '清空',
          type: 'normal',
          onClick: onBatchClear,
          // disabled: isBatchButton,
        },
      },
      {
        name: 'searchPanel',
      },
      {
        location: 'after',
        widget: 'dxButton',
        cssClass: 'refreshButton_Style',
        options: {
          icon: 'iconfont icon-refresh',
          onClick: async () => {
            await getBusinessType();
          },
        },
      },
    ],
  };
  const renderTreeList = () => {
    return (
      <>
        <TreeList
          className="business-type-table"
          ref={treeListRef}
          height={'100%'}
          key={tableKey}
          keyExpr={'typeName'}
          dataSource={dataSource}
          paging={{
            pageSize: 100000,
          }}
          scrolling={{
            useNative: false
          }}
          onSelectionChanged={(e: any) => {
            console.log(e, 'onSelectionChanged');
            const selectRow = e?.selectedRowsData;
            if (selectRow && selectRow.length) {
              // setSelectedRowsData(selectRow);
              // const treeViewScrollView = treeListRef?.current?.instance?.getScrollable();
              // treeScrollRef.current = treeViewScrollView.scrollTop();
              updateSelectedRowsData.current = selectRow
              // setBatchButton(false);
            } else {
              updateSelectedRowsData.current = null
              // setBatchButton(true);
            }
          }}
          onRowUpdated={(e: any) => {
            console.log(e, 'onRowUpdated');
            // setRowData(e.data);
          }}
          onOptionChanged={(e) => {
            const value = e.value;
            if (value && value.length) {
              console.log(value, 'onOptionChanged');
              const typeName = value[0]?.key;
              const mainType = value[0]?.data?.mainType;
              if (typeName) {
                updateRowData.current = {
                  typeName,
                  mainType
                }
              }
            }
          }}
          searchPanel={{
            visible: true,
            searchVisibleColumnsOnly: true,
            width: 150,
          }}
          editing={{
            allowUpdating: true,
            mode: 'cell',
          }}
          selection={{ mode: 'multiple' }}
          columns={columns}
          toolbar={toolbar}
        />
      </>
    );
  };
  //设置标准类型成功回调
  const onSetStandOk = (data: any) => {
    if (data && data.length) {
      const temp = [];
      for (let i = 0; i < data.length; i++) {
        const name = data[i].name;
        temp.push({
          id: name,
          name,
          key: i,
        });
      }
      setStandardSource(temp);
      getBusinessType();
    } else {
      setStandardSource([]);
    }
  };
  const onOk = () => {
    //新老数据diff算法，只更新变更的数据
    const newData = dataSource.slice();
    const rowData = updateRowData?.current ? updateRowData?.current : null;

    if (rowData) {
      for (let i = 0; i < newData.length; i++) {
        const { typeName } = newData[i];
        if (typeName === rowData.typeName) {
          newData[i].mainType = rowData.mainType;
        }
      }
    }
    for (let i = 0; i < defaultSource.length; i++) {
      const { typeName, mainType } = defaultSource[i];
      const newMainType = newData[i].mainType || null;
      if (typeName === newData[i].typeName && mainType !== newMainType) {
        updateBusinessType(newData[i].typeName, newMainType);
      }
    }
    setTableKey(nanoid10);
    if (okCallback) {
      okCallback(true);
    }
    // setClickBatchClear(false);
    setReportModalOpen(false);
  };
  const onCancel = () => {
    updateRowData.current = null;
    // setSelectedRowsData([]);
    updateSelectedRowsData.current = null
    treeListRef?.current?.instance?.clearSelection();
    treeListRef?.current?.instance?.refresh();
    setReportModalOpen(false);
    setTableKey(nanoid10);
    // setClickBatchClear(false);
  }
  return (
    <>
      <DevPopup.Logic
        ref={InputRef}
        visible={isReportModalOpen}
        height={'60vh'}
        width={'45vw'}
        title={'标准业务类型设置'}
        shading={true}
        onHiding={onCancel}
        onOK={onOk}
        onCancel={onCancel}
        className="business-type-body"
      >
        {renderTreeList}
      </DevPopup.Logic>
      <SetStandardType
        dbname={dbname}
        ref={setStandardTypeRef}
        dataList={standardSource}
        okCallback={onSetStandOk}
        cancelCallback={() => { }}
      />
    </>
  );
});
export default BusinessTypeModal;
